<?php
/**
 * ws服务api接口需要权限验证、需要登录验证公共基础类
 * User: raisound
 * Date: 2021/10/13
 */
namespace app\ws\controller;
use app\common\model\redis\RedisModel;
class AuthBase  extends Base
{
    public $userId = 0;
    public $userNumber = "";
    //当前请求的token
    public $xToken = "";
    public function initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Token,Content-Type, Content-Length, Authorization, Accept, X-Requested-With, Current-Page');
        header('Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE,PUT');
        parent::initialize();
        $this->xToken = $this->request->header(config("config.other.token"));
        if(!$this->xToken){
            return $this->returnResult(config("config.code.error"),'请输入token！');
        }
        if(!$this->isLogin()){
            return $this->returnResult(config("config.code.error"),'token失效！');
        }
    }


    /**
     * 判断用户是否已登陆
     * @return bool
     */
    public function isLogin(): bool
    {
        $RedisModel = new RedisModel();
        $userInfo = $RedisModel->getValue(config("redis.token_pre").$this->xToken);
        $userInfo = json_decode($userInfo,true);
        if(!$userInfo){
            return false;
        }
        if(!empty($userInfo['id']) && !empty($userInfo['user_number'])){
            $this->userNumber = $userInfo['user_number'];
            $this->userId = $userInfo['id'];
            return true;
        }
        return false;
    }
}
